#!/usr/bin/perl -w

my $TARGET = $ARGV[2];

QuitApp("Logic");
	
	
open(PSOUT, "/bin/ps -awwx |");
while(<PSOUT>)
{
	if($_ =~ /.*?(\d+)\s.*?EmagicEMIFW$/)
	{
		$EMI_PS_ID = $1;
		system(`kill "$EMI_PS_ID"`);
	}
	elsif($_ =~ /.*?(\d+)\s.*?EmagicA26A62mFW$/)
	{
		$A26A62m_PS_ID = $1;
		system(`kill "$A26A62m_PS_ID"`);
	}
	elsif($_ =~ /.*?\d+\s.*System Preferences\.app.*/) 
	{
		open(ASOUT, "/usr/bin/osascript -e \'tell application \"System Preferences\"\' -e \'activate\' -e \'try\' -e \'quit\' -e \'on error\' -e \'return (\"force quit\")\' -e \'end try\' -e \'end tell\' |" );
		close(ASOUT);
		last;
	}
}
close(PSOUT);




if (-e "$TARGET/System/Library/Extensions/EmagicEMI.kext")
{
	system(`rm "$TARGET/System/Library/Extensions.mkext"`);
	system(`rm -R "$TARGET/System/Library/Extensions/EmagicEMI.kext"`);
}
elsif (-e "$TARGET/System/Library/Extensions/EmagicEMI62USBAudio.kext")
{
	system(`rm "$TARGET/System/Library/Extensions.mkext"`);
	system(`rm -R "$TARGET/System/Library/Extensions/EmagicEMI62USBAudio.kext"`);
}
if (-e "$TARGET/Library/StartupItems/EmagicEMIFirmwareLoader")
{
	system(`rm -R "$TARGET/Library/StartupItems/EmagicEMIFirmwareLoader"`);
}
if (-e "$TARGET/Library/PreferencePanes/EMIPreferencePane.prefPane")
{
	system(`rm -R "$TARGET/Library/PreferencePanes/EMIPreferencePane.prefPane"`);
}
if (-e "$TARGET/Library/Audio/MIDI Devices/Emagic/Images/EMI62.tiff")
{
	system(`rm "$TARGET/Library/Audio/MIDI Devices/Emagic/Images/EMI62.tiff"`);
}
system(`find "$TARGET/Library/Documentation/Emagic" -type f -name EMI* -delete`);

exit (0);
##########################################################################

sub QuitApp
{
    my $APP = $_[0];

    my $IS_RUNNING = 0;
    my $PID = 0;
    my $rest;

    open(PSOUT, "/bin/ps -awwx |");
    while( <PSOUT> ) {
       if( /\/($APP.*?\.app)\// ) {
       $APPNAME = $1;
           ($PID, $rest) = split(' ');
           $IS_RUNNING = 1;
       }
    }
    close(PSOUT);

    if(1 eq $IS_RUNNING) {
        open(ASOUT, "/usr/bin/osascript -e \'tell application \"$APPNAME\"\' -e \'try\' -e \'quit\' -e \'on error\' -e \'set TheDialog to display dialog \"Please quit $APPNAME\" buttons \{\"Quit\"\}\' -e\'if button returned of TheDialog is \"Quit\" then\' -e \'tell application \"$APPNAME\"\' -e \'activate\' -e \'try\' -e \'quit\' -e \'end try\' -e \'end tell\' -e \'end if\' -e \'end try\' -e \'end tell\' |" );
        close(ASOUT);
    }
}
